import {
	login,
	logout,
	getUserInfo
} from '@/api/user'
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/cookie.js'
import {
	resetRouter
} from '@/router'


const getDefaultState = () => {
	return {
		token: getToken(),
		name: '',
		introduction: '',
		avatar: '',
		departmentName: '',
		email: '',
		phoneNumber: '',
		permission: []
	}
}

const state = getDefaultState()
const mutations = {
	/**
	 * 用户信息
	 */
	RESET_STATE: (state) => {
		Object.assign(state, getDefaultState())
	},
	/**
	 *token 
	 */
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	/**
	 * 用户昵称
	 */
	SET_NAME: (state, name) => {
		state.name = name
	},
	/**
	 * 头像信息
	 */
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	},
	/**
	 * 个人描述
	 */
	SET_INTRODUCTION: (state, introduction) => {
		state.introduction = introduction
	},
	/**
	 * 邮箱
	 */
	SET_EMAIL: (state, email) => {
		state.email = email
	},
	/**
	 * 手机号码
	 */
	SET_PHONENUMBER: (state, phoneNumber) => {
		state.phoneNumber = phoneNumber
	},
	/**
	 * 部门信息 
	 */
	SET_DEPARTMENTNAME: (state, departmentName) => {
		state.departmentName = departmentName
	},
	/**
	 * 角色信息
	 */
	SET_PERMISSION: (state, permission) => {
		state.permission = permission
	}
}

const actions = {
	// user login
	login({
		commit
	}, userInfo) {
		const {
			username,
			password
		} = userInfo
		return new Promise((resolve, reject) => {
			login({
				username: username.trim(),
				password: password
			}).then(response => {
				const {
					data
				} = response
				commit('SET_TOKEN', data)
				setToken(data)
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// get user info
	getInfo({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			getUserInfo().then(
				response => {
					const {
						data
					} = response
					commit('SET_NAME', data.username)
					commit('SET_AVATAR', data.avatar)
					commit('SET_INTRODUCTION', data.introduction)
					commit('SET_EMAIL', data.email)
					commit('SET_PHONENUMBER', data.phoneNumber)
					commit('SET_PERMISSION', data.permission)
					resolve(data)
				}).catch(error => {
				reject(error)
			})
		})
	},

	// user logout
	logout({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			console.log(state.token)
			logout().then(() => {
				removeToken() // must remove  token  first
				resetRouter()
				commit('RESET_STATE')
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},

	// remove token
	resetToken({
		commit
	}) {
		return new Promise(resolve => {
			commit('RESET_STATE')
			commit('SET_PERMISSION', [])
			removeToken() // must remove  token  first
			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
